package com.ruc.deke.utils;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;

public class UnitKit {

	public static String getOperatorIP(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("http_client_ip");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		// 如果是多级代理，那么取第一个ip为客户ip
		if (ip != null && ip.indexOf(",") != -1) {
			ip = ip.substring(ip.lastIndexOf(",") + 1, ip.length()).trim();
		}
		return ip;
	}

	@SuppressWarnings("deprecation")
	public static int getAge(Date bir) {
		// 拿到今天时间
		Date now = new Date();
		if (now.before(bir)) {// 如果生日在今天之后，永久返回-1
			return -1;
		}
		// 粗略年龄等于，现在年份减出生年份
		int age = now.getYear() - bir.getYear();
		// 倒退到出生年的今天
		now.setYear(bir.getYear());
		if (now.before(bir)) {// 如果出生年的今天比生日小，周岁要减1
			age -= 1;
		}
		return age;
	}

	/**
	 * 检查回访日期是否晚于当前时间
	 * 
	 * @author yuanyue(Acstream)
	 * @email yuangyue@qq.com
	 * @date 2016年7月29日 下午3:30:00
	 * @param visitDate
	 *            实现逻辑:首先获得当前时间 再获取回访时间 比较 返回结果
	 */
	public static boolean checkVisitDate(Date visitDate) {

		/**
		 * 获得当前时间
		 */
		Calendar calendarNow = Calendar.getInstance();// 取当前时间
		int yearNow = calendarNow.get(Calendar.YEAR);// 取当前时间年份
		int monthNow = calendarNow.get(Calendar.MONTH);// 取当前时间月份
		int dateNow = calendarNow.get(Calendar.DATE);// 取当前时间天

		/**
		 * 获得回访时间
		 */
		Calendar calendarVisitDate = Calendar.getInstance();
		calendarVisitDate.setTime(visitDate);// 取回访时间
		int yearVisitDate = calendarVisitDate.get(Calendar.YEAR);// 取回访时间年份
		int monthVisitDate = calendarVisitDate.get(Calendar.MONTH);// 取回访时间月份
		int dateVisitDate = calendarVisitDate.get(Calendar.DATE);// 取回访时间天

		/**
		 * 返回比较结果
		 */
		if ((yearNow <= yearVisitDate) && (monthNow <= monthVisitDate) && (dateNow <= dateVisitDate)) // 比较回访时间和当前时间，回访时间必须在当前时间之后或者就是今日
		{
			return true;
		} else {
			return false;
		}
	}

}
